package thread.threaddemo;

import java.time.LocalDateTime;

/**
 * @Author: wenjingyuan
 * @Date: 2022/10/31/21:13
 * @Description:
 */
public class ThreadDemo2 {
    private static final int COUNT=10;
    public static void main(String[] args) throws InterruptedException {
       //记录开始执行方法的时间戳
        long stime=System.currentTimeMillis();
        //单线程执行
        //singleThread();
        //多线程执行
        mutiThread();
        //记录结束执行方法的时间戳
        long etime=System.currentTimeMillis();
        System.out.println("执行的时间为："+(etime-stime));
    }

    /**
     * 多线程执行
     */
    private static void mutiThread() throws InterruptedException {
        //创建一个新线程
        Thread thread=new Thread(()->{
            for(int i=0;i<COUNT/2;i++){
                try {
                    //让线程休眠1s
                    Thread.sleep(1000);
                    System.out.println("执行for循环的时间为："+LocalDateTime.now());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //启动新线程
        thread.start();
        //主线程执行
        for(int i=0;i<COUNT/2;i++){
            try {
                //让线程休眠1s
                Thread.sleep(1000);
                System.out.println("执行for循环的时间为："+LocalDateTime.now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //等两个线程同时结束之后在记录时间
        thread.join();
    }

    /**
     * 单线程写法
     */
    private static void singleThread() {
        for(int i=0;i<COUNT;i++){
            try {
                //让线程休眠1s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
